from playwright.sync_api import sync_playwright


def scrape_douban_top250():
    with sync_playwright() as p:
        # 启动浏览器
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()
        
        try:
            # 访问豆瓣电影Top250页面
            page.goto("https://movie.douban.com/top250")
            page.wait_for_load_state("networkidle")
            
            # 打印表头
            print("{:<5} {:<50} {:<10}".format("排名", "电影名称", "评分"))
            print("-" * 70)
            
            # 提取前5部电影的信息
            for i in range(5):
                # 获取电影标题
                title_selector = f"#content > div > div.article > ol > li:nth-child({i+1}) .hd a span:first-child"
                movie_title = page.locator(title_selector).first.inner_text()
                
                # 获取评分
                rating_selector = f"#content > div > div.article > ol > li:nth-child({i+1}) .rating_num"
                rating = page.locator(rating_selector).first.inner_text()
                
                # 打印电影信息
                print("{:<5} {:<50} {:<10}".format(i+1, movie_title, rating))
            
        except Exception as e:
            print(f"发生错误: {e}")
        finally:
            browser.close()

if __name__ == "__main__":
    scrape_douban_top250()